package site.addzero.cli.autoinit.mac

import org.koin.core.annotation.Single
import site.addzero.cli.platform.PlatformTools.isMac
import site.addzero.cli.platform.PlatformTools.readBool
import site.addzero.cli.platform.PlatformTools.readBoolWithFlase
import site.addzero.cli.platform.PlatformTools.readBoolWithTrue
import site.addzero.cli.platform.runBoolean
import site.addzero.cli.platform.runCmd
import java.io.File

@Single
class AutoInitOhmyzsh {
    init {
        initializeOhMyZsh()
    }

    private fun initializeOhMyZsh() {
        // 检查是否为 Mac 系统
        if (!isMac()) return

        // 检查系统是否有 zsh
        val hasZsh = "which zsh 2>/dev/null".runBoolean()
        if (!hasZsh) return

        println("检测到 zsh")
        // 检查是否已安装 ohmyzsh
        val hasOhMyZsh = "[ -d ~/.oh-my-zsh ]".runBoolean()
        if (!hasOhMyZsh) {
            val readBoolean = readBoolWithTrue(prompt = "ohmyzsh 未安装,是否安装?")
            if (readBoolean == true) {
                // 安装 ohmyzsh
                val installCommand =
                    "\$(curl -fsSL https://gitee.com/allenjia09/ohmyzsh/raw/master/tools/install.sh)"
                installCommand.runCmd()
            }
        }

        // 检查并安装 zsh 插件
        checkAndInstallZshPlugins()
    }

    private fun checkAndInstallZshPlugins() {
        // 检查 zsh-autosuggestions 插件是否安装
        val autoSuggestionsInstalled = "brew list zsh-autosuggestions 2>/dev/null".runBoolean()
        if (!autoSuggestionsInstalled) {
            val installAutoSuggestions = readBool(
                prompt = "zsh-autosuggestions " +
                        "插件未安装，是否安装？",
                defaultValue = true
            )
            if (installAutoSuggestions == true) {
                "brew install zsh-autosuggestions".runCmd()
            }
        }

        // 检查 zsh-syntax-highlighting 插件是否安装
        val syntaxHighlightingInstalled = "brew list zsh-syntax-highlighting 2>/dev/null".runBoolean()
        if (!syntaxHighlightingInstalled) {
            val installSyntaxHighlighting = readBool(
                prompt = "zsh-syntax-highlighting" + " 插件未安装，是否安装？",
                defaultValue = true
            )
            if (installSyntaxHighlighting == true) {
                "brew install zsh-syntax-highlighting".runCmd()
            }
        }

        // 配置 .zshrc 文件
        configureZshrc()
    }

    private fun configureZshrc() {
        val homeDir = System.getProperty("user.home")
        val zshrcPath = "$homeDir/.zshrc"
        val zshrcFile = File(zshrcPath)

        // 获取系统架构
        val archResult = "uname -m".runCmd().output
        val isArmArchitecture = archResult.trim() == "arm64"

        val configLines = if (isArmArchitecture) {
            """
            |# ==================
            |# 判断操作系统架构并应用相关配置
            |# ==================
            |if [[ \$(uname -m) == 'arm64' ]]; then
            |    # ARM 架构的配置
            |    source /opt/homebrew/share/zsh-autosuggestions/zsh-autosuggestions.zsh
            |    source /opt/homebrew/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
            |else
            |fi
            """.trimMargin()
        } else {
            """
            |# ==================
            |# 判断操作系统架构并应用相关配置
            |# ==================
            |if [[ \$(uname -m) == 'arm64' ]]; then
            |    # ARM 架构的配置
            |    source /opt/homebrew/share/zsh-autosuggestions/zsh-autosuggestions.zsh
            |    source /opt/homebrew/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
            |else
            |    # Intel 架构的配置
            |    source /usr/local/share/zsh-autosuggestions/zsh-autosuggestions.zsh
            |    source /usr/local/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
            |fi
            """.trimMargin()
        }

        // 检查配置是否已存在
        val zshrcContent = if (zshrcFile.exists()) zshrcFile.readText() else ""

        // 使用更复杂的正则表达式来检查配置是否存在
        val hasConfig = zshrcContent.contains(Regex("""# =+.*判断操作系统架构并应用相关配置.*# =+""", RegexOption.DOT_MATCHES_ALL))

        if (!hasConfig) {
            val appendConfig = readBoolWithFlase(".zshrc 文件中缺少插件配置，是否添加？")
            if (appendConfig == true) {
                zshrcFile.appendText("\n$configLines\n")
                println("已将插件配置添加到 $zshrcPath")
            }
        } else {
            println("插件配置已存在于 $zshrcPath 文件中")
        }
    }
}
